package com.coc.serviceimpl.system;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.coc.core.utils.StringRelaUtils;
import com.coc.dao.system.SysUserDao;
import com.coc.entity.core.JsonResult;
import com.coc.entity.core.ResultTool;
import com.coc.entity.system.SysUser;
import com.coc.entity.system.SysUserRole;
import com.coc.service.system.SysUserService;
import com.coc.service.system.SysUserRoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 用户表(SysUser)表服务实现类
 *
 * @author songju
 * @since 2020-02-10 19:15:21
 */
@Service("sysUserService")
public class SysUserServiceImpl extends ServiceImpl<SysUserDao, SysUser> implements SysUserService {
    @Autowired
    private SysUserRoleService sysUserRoleService;
    @Override
    public SysUser selectByName(String userName) {
        SysUser one = this.getOne(new QueryWrapper<SysUser>().eq("username", userName));
        return one;
    }
   @Transactional
    @Override
    public JsonResult addUser(String json) {
        String roleIds = JSONObject.parseObject(json).getString("roleId");
        SysUser sysUser = JSONObject.parseObject(json, SysUser.class);
        //加密
        BCryptPasswordEncoder bp = new BCryptPasswordEncoder();
        String ps = bp.encode(sysUser.getPassword());
        sysUser.setPassword(ps);
        sysUser.setInsertTime(new Date());
        boolean save = save(sysUser);
        try {
        if (save){
            //保存该用户的角色
            QueryWrapper<SysUser> sqw = new QueryWrapper<>();
            sqw.eq("username",sysUser.getUsername());
            SysUser one = getOne(sqw);
            SysUserRole sr=null;
            if (StrUtil.isNotBlank(roleIds)&&roleIds.length()==1){
                sr = new SysUserRole();
                sr.setUserId(one.getId());
                sr.setRoleId(Integer.parseInt(roleIds));
                sysUserRoleService.save(sr);
            }else if (StrUtil.isNotBlank(roleIds)&&roleIds.length()>1){
                ArrayList<SysUserRole> sur = new ArrayList<>();
                List<String> rls = StringRelaUtils.strToList(roleIds);
                for (String rl:rls){
                    sr = new SysUserRole();
                    sr.setUserId(one.getId());
                    sr.setRoleId(Integer.parseInt(rl));
                    sur.add(sr) ;
                }
                sysUserRoleService.saveBatch(sur);
            }
        }else {
            return ResultTool.fail();
        }
        }catch (Exception e){
            return ResultTool.fail();
        }

        return ResultTool.success();
    }

    @Override
    public SysUser GetCurrUser() {
        User principal = (User) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        String username = principal.getUsername();
        if (StrUtil.isNotBlank(username)){
            SysUser sysUser = selectByName(username);
            return sysUser;
        }else {
            return null;
        }
    }
    @Transactional
    @Override
    public JsonResult editUser(String json) {
        SysUser sysUser = JSONObject.parseObject(json, SysUser.class);
        JSONObject jsonObject = JSONObject.parseObject(json);
        String roleIds = jsonObject.getString("roleId");
        String phone = jsonObject.getString("phone");
        UpdateWrapper<SysUser> suw = new UpdateWrapper<>();
        suw.set("realname",sysUser.getRealname());
        suw.set("mobile",phone);
        suw.set("insert_time",new Date());
        suw.set("email",sysUser.getEmail());
        suw.eq("id",sysUser.getId());
        //更新sysUser数据
        update(suw);
        sysUserRoleService.removeById(sysUser.getId());
        SysUserRole sp=null;
        if (StrUtil.isNotBlank(roleIds)){
            if (roleIds.length()==1){
                SysUserRole sysUserRole = new SysUserRole();
                sysUserRole.setUserId(sysUser.getId());
                sysUserRole.setRoleId(Integer.parseInt(roleIds));
                sysUserRoleService.save(sysUserRole);
            }else {
                ArrayList<SysUserRole> sur = new ArrayList<>();
                List<String> rls = StringRelaUtils.strToList(roleIds);
                for (String rl:rls){
                    sp=new SysUserRole();
                    sp.setUserId(sysUser.getId());
                    sp.setRoleId(Integer.parseInt(rl));
                    sur.add(sp);
                }
                sysUserRoleService.saveBatch(sur);
            }
        }
        return ResultTool.success();
    }
}